package com.quanyan.user.service.impl;

import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.utils.Limit;
import com.quanyan.user.constants.UserConstants;
import com.quanyan.user.mapper.*;
import com.quanyan.user.model.db.*;
import com.quanyan.user.model.vo.request.ReqQueryUserInfo;
import com.quanyan.user.model.vo.request.ReqQueryUserInterest;
import com.quanyan.user.model.vo.response.QueryUserDetail;
import com.quanyan.user.model.vo.response.QueryUserInfo;
import com.quanyan.user.model.vo.response.QueryUserInterest;
import com.quanyan.user.service.AdminService;
import com.quanyan.user.utils.CriteriaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by yue.yuan on 2016/7/12.
 */
@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Autowired
    private TbAdminGroupMapper tbAdminGroupMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private UserExtMapper userExtMapper;

    @Autowired
    private TbUserExtMapper tbUserExtMapper;

    @Autowired
    private UserInterestMapper userInterestMapper;

    @Autowired
    private TbUserMapper tbUserMapper;

    //查询分组列表
    @Override
    public List<TbAdminGroup> selectGroupList()
    {
        return tbAdminGroupMapper.selectByExample(null);
    }

    //删除用户组
    public void deleteGroup(Integer groupId)
    {
        tbAdminGroupMapper.deleteByPrimaryKey(groupId);
    }

    //添加用户组
    public void addGroup(TbAdminGroup group)
    {
        tbAdminGroupMapper.insert(group);
    }

    /**
     * 根据ID查询该用户的附属信息
     * @param userId
     * @return
     */
    public TbUserExt selectUserExtById(Integer userId)
    {
        return tbUserExtMapper.selectByPrimaryKey(userId);
    }

    @Override
    public QueryUserDetail selectUserDetailById(Integer userId)
    {
        QueryUserDetail result = new QueryUserDetail();
        TbUserExt tbUserExt = this.selectUserExtById(userId);
        result.setTbUserExt(tbUserExt);

        List<String> list = userInterestMapper.selectByUserId(userId);
        result.setUserInterests(list);
        return result;
    }

    /**
     * 分页查询用户基本信息
     * @param req
     * @return
     */
    @Override
    public PageObj<List<QueryUserInfo>> queryUserInfoByPage(ReqQueryUserInfo req)
    {
        CriteriaUtil example = new CriteriaUtil();
        CriteriaUtil.Criteria criteria = example.createCriteria();
        if(null != req.getLarkCode())
        {
            criteria.addCriterion("t4.lark_code = ", req.getLarkCode(), "larkCode");
        }
        if(null != req.getBeginRegTime() && null != req.getEndRegTime())
        {
            criteria.addCriterion("t1.reg_time between",req.getBeginRegTime(), req.getEndRegTime(), "regTime");
        }
        if(null != req.getMobile() && !"".equals(req.getMobile()))
        {
            criteria.addCriterion("t1.mobile = ", req.getMobile(), "mobile");
        }
        if(null != req.getGender())
        {
            criteria.addCriterion("t1.gender = ", req.getGender().byteValue(), "gender");
        }
        if(null != req.getName() && !"".equals(req.getName()))
        {
            criteria.addCriterion("t1.name = ", req.getName(), "name");
        }
        if(null != req.getProvinceId())
        {
            criteria.addCriterion("t1.province_id = ", req.getProvinceId(), "provinceId");
        }
        if(null != req.getAreaId())
        {
            criteria.addCriterion("t1.area_id = ", req.getAreaId(), "areaId");
        }
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        //example.setOrderByClause(" t1.reg_time desc ");
        Integer total = userInfoMapper.countUserInfoByCriteria(example);
        if(((pageNum-1)*pageSize) > total)
        {
            pageNum = 1;
        }
        example.setLimit(Limit.buildLimit(pageNum, pageSize));
        List<QueryUserInfo> list = userInfoMapper.queryUserInfoByPage(example);
        return PageObj.create(total, pageNum, pageSize, list);
    }

    /**
     * 分页查询
     * @param req
     * @param isRegister
     * @return
     */
    @Override
    public PageObj<List<QueryUserInterest>> selectUserInterestsByPage(ReqQueryUserInterest req, boolean isRegister)
    {
        TbUserInterestExample example = new TbUserInterestExample();
        TbUserInterestExample.Criteria criteria = example.createCriteria();
        criteria.andIsDeleteEqualTo(UserConstants.USER_INTEREST_IS_NOT_DELETE);
        Integer uid = null;
        if(isRegister)
        {
            //计算总数时用uid计数
            example.setRegister(true);
            criteria.andIsRegisterEqualTo(UserConstants.USER_INTEREST_IS_REGISTER);
            //精确手机号，设备号，百灵鸟ID  调用TbUserMapper获取uid
            uid = getUserIdByInfo(req);
            if(null != uid)
            {
                example.setGroupByClause("t1.uid");
                criteria.andUidEqualTo(uid);
                criteria.andIsRegisterEqualTo(UserConstants.USER_INTEREST_IS_REGISTER);
            }
        }
        else
        {
            //游客
            example.setRegister(false);
            example.setGroupByClause("t1.dsn");
            criteria.andIsRegisterEqualTo(UserConstants.USER_INTEREST_IS_NOT_REGISTER);
        }

        //时间范围
        if(null != req.getStartUpdate() && null != req.getEndUpdate())
        {
            criteria.andUpdateTimeBetween(req.getStartUpdate(), req.getEndUpdate(), "t1.");
        }

        //选择兴趣标签
        if(null != req.getInterestIds() && req.getInterestIds().size() > 0)
        {
            criteria.andInterestIdIn(req.getInterestIds());
        }
        int pageNum = req.getPageNum();
        int pageSize = req.getPageSize();
        /*公共的条件*/
        example.setDistinct(true);
        example.setOrderByClause(" t1.update_time asc ");

        Integer total = userInterestMapper.countByExample(example);
        if(((pageNum-1)*pageSize) > total)
        {
            pageNum = 1;
        }
        example.setLimit(Limit.buildLimit(pageNum, pageSize));
        return PageObj.create(total, pageNum, pageSize, userInterestMapper.selectByPage(example));
    }

    private Integer getUserIdByInfo(ReqQueryUserInterest req)
    {
        if(null != req.getLarkCode() && !"".equals(req.getLarkCode()))
        {
            TbUserExtExample userExtExample = new TbUserExtExample();
            TbUserExtExample.Criteria userExtCriteria = userExtExample.createCriteria();
            tbUserExtMapper.selectByExample(userExtExample);
            Integer userId = userExtMapper.selectUserIdByLarkCode(req.getLarkCode());
            if(null != userId)
            {
                return userId;
            }
        }

        TbUserExample userExample = new TbUserExample();
        TbUserExample.Criteria userCriteria = userExample.createCriteria();
        String mobile = req.getMobile();
        if(null != mobile && !"".equals(mobile))
        {
            userCriteria.andMobileEqualTo(mobile);
        }
        String dsn = req.getDsn();
        if(null != dsn && !"".equals(dsn))
        {
            userCriteria.andDsnEqualTo(dsn);
        }

        List<TbUser> users = tbUserMapper.selectByExample(userExample);
        if(null == users || users.size() != 1)
        {
            return null;
        }
        TbUser user = users.get(0);
        if(null == user)
        {
            return null;
        }
        return (null == user.getId()) ? null : user.getId();
    }

}
